#!/usr/bin/python
# -*- coding: utf-8 -*-
import os
import gtk
from gtk import glade

import app
import ftp
import icons


class ConnectDialog:
    def __init__(self, appinst, browser=None):
        self.appinst = appinst
        self.config = appinst.config
        self.browser = browser
        
        self.wTree = glade.XML(app.glade_file, "dialog_connect")
        self.window = self.wTree.get_widget('dialog_connect')
        self.combobox_sites = self.wTree.get_widget('combobox_sites')
        self.entry_host = self.wTree.get_widget('entry_host')
        self.entry_user = self.wTree.get_widget('entry_user')
        self.entry_password = self.wTree.get_widget('entry_password')
        self.checkbutton_use_ssl = self.wTree.get_widget('checkbutton_use_ssl')
        self.checkbutton_force_ssl = self.wTree.get_widget('checkbutton_force_ssl')
        self.checkbutton_passive = self.wTree.get_widget('checkbutton_passive')
        
        _signals = {'close': lambda w: self.appinst.close_window(self),
                    'cancel_clicked': lambda w: self.appinst.close_window(self),
                    'save_clicked': self.save,
                    'connect_clicked': lambda w: self.connect(),
                    'combobox_sites_changed': self.select_site,
                    'button_delete_clicked': self.delete_selected,
                    'entry_user_activate': lambda w: self.connect(),
                    'entry_host_activate': lambda w: self.connect(),
                    'entry_password_activate': lambda w: self.connect(),
                   }
        self.wTree.signal_autoconnect(_signals)
        
        self.window.set_icon(icons.from_theme("gtk-network", 16))
        
        self.store = gtk.ListStore(str)
        self.combobox_sites.set_model(self.store)
        self.fill_site_menu()
        self.window.show_all()
        
    def close(self, *w):
        # destroy reference to this object, if browser has that is
        if self.browser:
            self.browser.connect_dialog = None
        self.window.destroy()
        
    def fill_site_menu(self):
        """Fills the combobox with the saved sites."""
        self.store.clear()
        for x in self.config.sections(): 
            if x.startswith("site:"):
                self.store.append([x[5:]])
    
    def delete_selected(self, w):
        """Delete selected site from config."""
        iter = self.combobox_sites.get_active_iter()
        if not iter: return
        site = self.store.get_value(iter, 0)
        self.config.remove_section('site:'+site)
        self.fill_site_menu()
        
    def save(self, w):
        dTree = glade.XML(app.glade_file, "dialog_site_name")
        dwindow = dTree.get_widget('dialog_site_name')
        dentry = dTree.get_widget('entry_name')
        dpass = dTree.get_widget('checkbutton_password')
        if self.entry_user.get_text():
            dentry.set_text('@'.join([
                self.entry_user.get_text(), 
                self.entry_host.get_text()
            ]))
        else:
            dentry.set_text(self.entry_host.get_text())
            
        def doEnd(*args):
            dwindow.destroy()    
            
        def doSave(*args):
            cfgstr = 'site:'+dentry.get_text()
            if not self.config.has_section(cfgstr):
                self.config.add_section(cfgstr)
            self.config.set(cfgstr, 'hostname', self.entry_host.get_text())
            self.config.set(cfgstr, 'username', self.entry_user.get_text())
            if dpass.get_active():
                self.config.set(cfgstr, 'password', self.entry_password.get_text())
            self.config.set(cfgstr, 'use_ssl',
                 str(self.checkbutton_use_ssl.get_active()))
            self.config.set(cfgstr, 'force_ssl',
                 str(self.checkbutton_force_ssl.get_active()))
            self.config.set(cfgstr, 'passive',
                str(self.checkbutton_passive.get_active()))
            doEnd()
            
        _signals = {'button_save_clicked': doSave,
                    'button_cancel_clicked': doEnd}
        dTree.signal_autoconnect(_signals)
        dwindow.show_all()
        
    def connect(self):
        """Connect with the information given.
        Create a FTPServer object and tell parent to use it."""
        host = self.entry_host.get_text()
        if ':' in host:
            host, port = host.split(':', 1)
            port = int(port)
        else:
            port = 21
        
        s = dict(
            username = self.entry_user.get_text() or "anonymous",
            password = self.entry_password.get_text() or
                self.config.get("ftp", "anonymous_password"),
            port = port,
            protocol = self.checkbutton_use_ssl.get_active() and "ftp+ssl" or "ftp",
            passive = self.checkbutton_passive.get_active(),
        )
        server = ftp.Server(host, **s)
        self.window.hide_all()
        if self.browser:
            self.browser.connect(server)
        else:
            self.appinst.new_browser().connect(server)
        self.appinst.close_window(self)
        
    def select_site(self, cb):
        site = cb.get_active_text()
        app.debug("Site selected: " + site, "connectdialog")
        
        cfgstr = 'site:'+site
        
        host = self.config.get(cfgstr, 'hostname')
        if self.config.has_option(cfgstr, 'port'):
            port = self.config.getint(cfgstr, 'port')
            if port != 21:
                host += ":%s"%str(port)
            
        user = self.config.get(cfgstr, 'username')
        
        self.entry_host.set_text(host)
        self.entry_user.set_text(user)
        
        if self.config.has_option(cfgstr, 'password'):
            p = self.config.get(cfgstr, 'password')
            self.entry_password.set_text(p)
        else:
            self.entry_password.set_text('')
        
        # de-activate checkbutton_use_ssl if False    
        if self.config.has_option(cfgstr, 'use_ssl'):
            self.checkbutton_use_ssl.set_active(
                self.config.getboolean(cfgstr, 'use_ssl'))
            
        # activate checbutton_force_ssl if set
        if self.config.has_option(cfgstr, 'force_ssl'):
            self.checkbutton_force_ssl.set_active(
                self.config.getboolean(cfgstr, 'force_ssl'))

        # set passive
        if self.config.has_option(cfgstr, 'passive'):
            self.checkbutton_passive.set_active(
                self.config.getboolean(cfgstr, 'passive'))
